<div class="menu">
    <ul>
        {{- $displayedNode := . }}
        {{- template "menu-loop" dict "currentnode" .Site.Home "displayednode" $displayedNode }}
    </ul>
</div>

<!-- Template -->
{{- define "menu-loop" }}
    {{- $currentNode := .currentnode }}
    {{- $displayedNode := .displayednode }}
    {{- with .currentnode}}
        {{- $numberOfPages := (add (len .Pages) (len .Sections)) }}
        <li>
            <a class="{{- if .IsAncestor $displayedNode }} ancestor{{- end }}
                {{- if eq .RelPermalink $displayedNode.RelPermalink}} active{{- end }}
                {{- if .IsSection}} section{{- end }}" href="{{- .RelPermalink }}">
                {{- if .LinkTitle }}
                    {{- .LinkTitle }}
                {{- else }}
                    {{- $noparent := .File.Dir }}
                    {{- if .Parent.File }}
                        {{- $noparent = replace .File.Dir .Parent.File.Dir "" }}
                    {{- end }}
                    {{- replaceRE "/" "-" $noparent }}{{- .File.TranslationBaseName }}
                {{- end }}
            </a>
            {{- if and (ne $numberOfPages 0) (or (.IsDescendant $displayedNode) (.IsAncestor $displayedNode) (.InSection $displayedNode)) }}
                <ul class="{{- if .IsAncestor $displayedNode}} ancestor{{- end }}
                    {{- if ne $numberOfPages 0 }} parent{{- end }}">
                    {{- $subElements := dict }}
                    {{- range .Site.Pages }}
                        {{- if and (eq .Parent $currentNode) (.IsDescendant $currentNode) }}
                            {{- $subElements = merge $subElements (dict (string .) . ) }}
                        {{- end }}
                    {{- end }}
                    {{- range $subElements }}
                        {{- template "menu-loop" dict "currentnode" . "displayednode" $displayedNode }}
                    {{- end }}
                </ul>
            {{- end }}
        </li>
    {{- end }}
{{- end }}
